<template>
  <view>
    <u-navbar
      title="投注列表"
      title-color="#fff"
      title-size="32"
      :background="{
        backgroundColor:'#CB3A35'
      }"
      back-icon-color="#fff"
    >
    </u-navbar>

    <!-- 顶部区域 -->
    <view class="header">
      <view
        class="left"
        @click="handleAdd"
      >+ 添加赛事</view>
      <view
        class="right"
        @click="handleClear"
      >清空重选</view>
    </view>

    <!-- 中部赛事区域 -->

    <view class="content">
      <view
        class="item"
        v-for="item in checkList"
        :key="item.matchId"
        @click="handleClickRow(item)"
      >

        <view class="item-top">

          <view class="left">
            <u-icon
              @click.native.stop="handleDelete(item)"
              color="#DDDDDD"
              name="close-circle-fill"
              size="38"
            ></u-icon>
          </view>
          <view class="right">
            <text> {{item.homeTeamAbbName}}</text>
            <text>VS</text>
            <text> {{item.awayTeamAbbName}}</text>

          </view>
        </view>

        <view class="item-bottom">
          <view class="left">
            <view> {{item.matchNumStr.slice(2)}}</view>
            <view>{{item.matchWeek}}</view>
          </view>
          <!-- <view class="mid">让平</view> -->
          <view class="mid">{{reStr(item.props)}}</view>
          <view class="right">
            <text>
              胆
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部区域 -->
    <view class="bottom">
      <view class="one">
        <view
          class="left"
          @click="show=!show"
        >
          <text v-if="show">返回</text>
          <text v-else class="ctitCss">{{chTit}}</text>
          <u-icon
            name="arrow-down"
            size="24"
          ></u-icon>
        </view>

        <view class="mid">
          <text>倍</text>
						<u-number-box :min="1" v-model="multiply"></u-number-box>
          <text>数</text>
        </view>
        <view class="right">
          <text @click='handleConfirmopen(demoReq)'>奖金优化</text>
          <u-icon
            name="arrow-right"
            size="24"
          ></u-icon>
        </view>
      </view>

      <view
        class="wrap"
        v-show="show"
      >
        <view class="title">
          自由过关
        </view>
        <u-row gutter="20">
          <u-col
            span="4"
            v-for="item in ziData"
            :key="item.id"
          >
            <view
              :class="{'on':item.checked}"
              class="col-item"
              @click="ziCli(item)"
            >{{item.val}}</view>
          </u-col>
        </u-row>
				<view class="title" v-if="duoData.length > 0">
				  多串过关
				</view>
				<u-row gutter="20" v-if="duoData.length > 0">
				  <u-col
				    span="4"
				    v-for="item in duoData"
				    :key="item.id"
				  >
				    <view
				      :class="{'on':item.val === checked.val}"
				      class="col-item"
				      @click="duoCli(item)"
				    >{{item.val}}</view>
				  </u-col>
				</u-row>
      </view>

      <view class="two">
        <view class="top" v-if="teShow">
          {{betCnt}}注{{betAmount}}元 预计奖金：{{minLottery}} ~ {{maxLottery}}元
        </view>
				<view class="top" v-else>
				  0注0元 预计奖金：0 ~ 0元
				</view>
        <view class="bot">
          预计奖金仅供参考，请以实际票为准
        </view>

      </view>
      <view class="three">
        <view class="left">
          <u-icon
            name="zhuanfa"
            color="#CB3A35"
            size="30"
            top="3"
          ></u-icon>

          <text>发布跟单</text>
        </view>
        <view class="right" @click="conBetting()">确认投注</view>
      </view>
    </view>
      <!-- <view @click="calculateBet(demoReq,betType,standardValue,combineValue)">
        (点击测试函数)
      </view> -->

    <SelectModal
      :visible.sync="visible"
      :data="data"
    />
  </view>

</template>

<script>
import Decimal from 'decimal.js';
import chuanJson from "@/data/chuan.js";
import SelectModal from "@/components/SelectModal";
export default {
  components: {
    SelectModal,
  },
  provide() {
    return {
      parent: this,
    };
  },
  data() {
    return {
			nameData: chuanJson.data.tyna,
			chuanData: chuanJson.data.chArr,
      show: false,
      visible: false,
      checked: {},
      data: {},
			teShow: true,
			chTit: '请选择',
      ziData: [], // 自由数组
      duoData: [], // 多串数组
      checkList: [],

      //计算赔率所需变量
      demoReq: [{
          matchId: 1008467, //比赛id
          matchNumStr: "周三001", //投注场次
          homeTeamAbbName: "凯尔特人", //主队
          awayTeamAbbName: "阿尔克马", //客队
          choosed: [{
              type: "hhad.h", //选中的投注类型
              odds: "2.47", //赔率
          }]
				}, {
          matchId: 1008468, //比赛id
          matchNumStr: "周三002", //投注场次
          homeTeamAbbName: "伯明翰", //主队
          awayTeamAbbName: "伯恩茅斯", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "3.65", //赔率
          }]
				}, {
          matchId: 1008469, //比赛id
          matchNumStr: "周三003", //投注场次
          homeTeamAbbName: "testZhu3", //主队
          awayTeamAbbName: "testKe3", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "4.20", //赔率
          }]
				}, {
          matchId: 1008470, //比赛id
          matchNumStr: "周三004", //投注场次
          homeTeamAbbName: "testZhu4", //主队
          awayTeamAbbName: "testKe4", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "3.40", //赔率
          }]
				}, {
          matchId: 1008471, //比赛id
          matchNumStr: "周三005", //投注场次
          homeTeamAbbName: "testZhu5", //主队
          awayTeamAbbName: "testKe5", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "1.92", //赔率
          }]
				}, {
          matchId: 1008472, //比赛id
          matchNumStr: "周三006", //投注场次
          homeTeamAbbName: "testZhu6", //主队
          awayTeamAbbName: "testKe6", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "1.57", //赔率
          }]
				}, {
          matchId: 1008473, //比赛id
          matchNumStr: "周三007", //投注场次
          homeTeamAbbName: "testZhu7", //主队
          awayTeamAbbName: "testKe7", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "6.50", //赔率
          }]
				}, {
          matchId: 1008474, //比赛id
          matchNumStr: "周三008", //投注场次
          homeTeamAbbName: "testZhu8", //主队
          awayTeamAbbName: "testKe8", //客队
          choosed: [{
              type: "crs.s00s02", //选中的投注类型
              odds: "3.05", //赔率
          }]
				}
			],

      betType: 1, //1 标准过关  2 组合过关

      standardValue: [], //2串1、3串1 例子 2, 3, 4, 5, 6, 7, 8

      combineValue: "", // 例子 3串4

      result: [], //存放组合结果，

      betCnt: 0, //几注

      multiply: 1, //倍数

      betAmount: 1, //投注金额

      minLottery: 1, //最小奖金

      maxLottery: 0, //最大奖金

      minOdds: Number.MAX_VALUE, //组合最小赔率

      maxOdds: 0, //组合最大赔率


      resultInfo:{ },//详情、奖金优化页面


    };
  },
  onLoad({ query }) {
    const checkList = JSON.parse(decodeURIComponent(query));
    this.checkList = checkList;
		let _this = this
		this.chuanData.forEach((item) => {
			if (this.checkList.length === item.id) {
				_this.ziData = item.zi
				_this.duoData = item.duo
			}
		})
		this.chTit = String(this.checkList.length) + '串1'
		this.standardValue.push(Number(this.checkList.length))
		this.ziData.forEach((item) => {
			if (item.val === this.chTit) {
				item.checked = true
			}
		})
		this.$forceUpdate()
  },
	watch: { // 监听数组改动
	    checkList: {
	      handler(val) {
					if (val.length > 0) {
						val.forEach((item)=> {
              let a,b,c
              item.choosed = []
							item.props.forEach((ii) => {
                let obj = {}
								a = ii.split('.')[0]
								b = ii.split('.')[1]
                obj.type = ii
                obj.odds = Number(item[a][b])
                item.choosed.push(obj)
							})
						})
						this.chTit = String(this.checkList.length) + '串1'
						this.betType = 1
						this.standardValue = []
						this.standardValue.push(Number(this.checkList.length))
						this.ziData.forEach((item) => {
							item.checked = false
							if (item.val === this.chTit) {
								item.checked = true
							}
						})
						this.$forceUpdate()
					}
					this.demoReq = val
					console.log('watch-val', val, this.demoReq)
					this.calculateBet(this.demoReq,this.betType,this.standardValue,this.combineValue)
	      },
	      deep: true,
	    },
			multiply: {
				handler(val) {
					this.calculateBet(this.demoReq,this.betType,this.standardValue,this.combineValue)
				}
			}
	  },
  methods: {
	  handleConfirmopen(val) {
			localStorage.setItem('cht', this.chTit)
			const query = encodeURIComponent(JSON.stringify(this.resultInfo));
			let isGopen = true
			this.checkList.forEach((item) => {
				item.choosed.forEach((ii) => {
					let si = ii.type.split('.')[0]
					if (si !== 'had' && si !== 'hhad') {
						isGopen = false
						return false
					}
				})
			})
			if (this.betCnt <101 && (this.betType === 1 && this.standardValue.length === 1) && isGopen) {
				uni.navigateTo({
					url: `/pages/bet-list/touzhu?query=${query}`,
				});
			} else {
				uni.showToast({
						title: '此玩法不支持奖金优化',
						icon: 'none',
						duration: 1000
				});
				return false
			}
	  },
		reStr (list) {
      if (list.length > 0) {
        let str = ''
        list.forEach((iii) => {
          this.nameData.forEach((ii) => {
            if (iii === ii.type) {
              str = str + ii.name + ' '
            }
          })
        })
        return str
      }
		},
    handleClickRow(item) {
      // this.data = item;
      // this.visible = true;
    },

    // 单个表格点击
    handleClickCell(el, prop) {
      const index = this.checkList.findIndex(
        (item) => item.matchId === el.matchId
      );
      if (index === -1) {
        this.checkList.push({
          ...el,
          props: [prop],
        });
      } else {
        const pIndex = this.checkList[index].props.indexOf(prop);
        if (pIndex === -1) {
          this.checkList[index].props.push(prop);
        } else {
          this.checkList[index].props.splice(pIndex, 1);
          if (!this.checkList[index].props.length) {
            this.checkList.splice(index, 1);
          }
        }
      }
    },

    // 表格是否勾选
    isChecked(el, prop) {
      const item = this.checkList.find((item) => item.matchId === el.matchId);
      if (item) {
        const index = item.props.indexOf(prop);
        return index !== -1;
      }

      return false;
    },

    // 删除按钮
    handleDelete(item) {
      const index = this.checkList.findIndex(
        (el) => el.matchId === item.matchId
      );
      this.checkList.splice(index, 1);
    },

    // 添加赛事按钮
    handleAdd() {
      uni.navigateBack({
        delta: 1,
      });
    },

    handleClear() {
      uni.navigateTo({
        url: "/pages/events-list/index",
      });
    },

    ziCli(item) {
			if (item.checked) {
				item.checked = false
				let nV = Number(item.val.split('串')[0])
				this.standardValue.splice(this.standardValue.findIndex(i => nV === i), 1)
			} else {
				item.checked = true
				this.standardValue.push(Number(item.val.split('串')[0]))
			}
			if (this.standardValue.length > 0) {
				this.chTit = ''
				this.standardValue = this.standardValue.sort()
				this.standardValue.forEach((item) => {
					this.chTit = this.chTit + String(item) + '串1,'
				})
				this.chTit = this.chTit.slice(0,this.chTit.length-1)
			}
			this.betType = 1
			this.checked = {}
		  this.combineValue = ''
			this.teShow = true
			if ((this.betType === 1 && this.standardValue.length === 0) || (this.betType === 2 && this.combineValue === '')) {
				uni.showToast({
				    title: '请选择玩法',
						icon: 'none',
				    duration: 1000
				});
				this.teShow = false
				return false
			}
			this.calculateBet(this.demoReq,this.betType,this.standardValue,this.combineValue)
			this.$forceUpdate()
			console.log('zicli-stvalue', this.betType, this.standardValue, this.combineValue)
    },

    duoCli(item) {
			if (this.checked === item) {
				this.checked = {}
				this.betType = 2
				this.combineValue = ''
				if ((this.betType === 1 && this.standardValue.length === 0) || (this.betType === 2 && this.combineValue === '')) {
					uni.showToast({
					    title: '请选择玩法',
							icon: 'none',
					    duration: 1000
					});
					this.chTit = '请选择'
					this.teShow = false
					return false
				}
			} else {
				this.checked = item
				this.teShow = true
			}
			this.betType = 2
			this.combineValue = item.val
			this.chTit = item.val
			this.ziData.forEach((item) => {
				item.checked = false
			})
		  this.standardValue = []
			this.calculateBet(this.demoReq,this.betType,this.standardValue,this.combineValue)
			this.$forceUpdate()
			console.log('duocli-stvalue', this.betType, this.standardValue, this.combineValue)
    },
		conBetting () {
		   if (this.standardValue.length === 0 && this.combineValue === '') {
		    uni.showToast({
		        title: '请选择玩法',
		      icon: 'none',
		        duration: 1000
		    });
		    return false
		   } else if (this.betAmount < 10) {
				uni.showToast({
				    title: '投注金额必须大于10元',
						icon: 'none',
				    duration: 1000
				});
				return false
			}
		   console.log('cobetting')
		   // 接下来跳转投注详情页面代码
		   this.resultInfo.time = new Date()
		   this.resultInfo.betType = this.chTit
		   const query = encodeURIComponent(JSON.stringify(this.resultInfo));
		   uni.navigateTo({
		     url: `/pages/bet-list/xiangqing?query=${query}`,
		   });
		  },
		//这边是计算赔率的核心区域

    //核心函数
    calculateBet: function (arr, type, standardValue, combineValue) {
        //初始化
        this.result = [];
        this.minLottery=1; //最小奖金
        this.maxLottery= 0;//最大奖金
        this.minOdds= Number.MAX_VALUE; //组合最小赔率
        this.maxOdds=0;//组合最大赔率

        var len = arr.length;
        var m = combineValue.split("串")[0];
        var value = [];
        //分类
        if (type == 1) {
            //标准过关
            this.calculateMchuanN(arr, standardValue)
        } else if (type == 2) {
            //组合过关
            //计算value
            value = this.calculateValue(combineValue)
            if (len > m) {
                this.calculateMchuanNRecursion(arr, value, m)
            } else if (len == m) {
                this.calculateMchuanN(arr, value)
            }
        }
        this.calculateResult()
    },

    arrangement: function (arr, N, tmp, result) {
        for (let i = 0; i < arr[N].choosed.length; ++i) {
            //N表示第几个数组，如arr[0]，表示第一个数组a。arr[0][0]，表示数组a的第一个元素
            tmp.push({
                ...arr[N].choosed[i],
                matchId: arr[N].matchId,
                matchNumStr: arr[N].matchNumStr,
                homeTeamAbbName: arr[N].homeTeamAbbName,
                awayTeamAbbName: arr[N].awayTeamAbbName,
            })
            //arr.length为合并前的数组的数量
            if (N < arr.length - 1) {
                this.arrangement(arr, N + 1, tmp, result)
            } else {
                let oneResult = [];
                let tmpOdds = 1 //中间临时变量

                for (let j = 0; j < arr.length; j++) {
                    oneResult.push(tmp[j])
                    tmpOdds = new Decimal(tmpOdds).mul(new Decimal(tmp[j].odds)).toNumber()
                }
                if (tmpOdds < this.minOdds) {
                    this.minOdds = tmpOdds
                }
                if (tmpOdds > this.maxOdds) {
                    this.maxOdds = tmpOdds
                }
                let perLottery = new Decimal(2).mul(new Decimal(tmpOdds)).toNumber().toFixed(2)
                result.push({
                    result: oneResult,
                    perLottery: perLottery,
                    multiply: this.multiply
                })
            }
            //最后一位出栈
            tmp.pop()
        }
    },
    //start：为每个数的起始索引号。
    //count: 初始值为任意取出的元素的个数N，每一次递归count会减一，用于计算每个数的最后一位索引号和判断递归是否继续。
    //Num为常数，值是任意取出的元素的个数N,用于最后结果的输出。
    combination: function (arr, start, count, Num, res, stack) {
        //用递归实现，把N个循环用同一个循环实现
        for (let i = start; i < arr.length - count + 1; i++) {
            //记录索引号
            res[count - 1] = i;
            if (count - 1 == 0) {
                let oneResult = []
                for (let j = Num - 1; j >= 0; j--) {
                    oneResult.push(arr[res[j]])
                }
                stack.push(oneResult)
            } else {
                this.combination(arr, i + 1, count - 1, Num, res, stack)
            }
        }
    },
    //计算 m串n核心函数
    //arr 原数组
    //standrandValue 数组 m串1的m
    calculateMchuanN: function (arr, standardValue) {
        standardValue.map((m) => {
            //存放索引号
            let res = []

            //存放最后的结果
            let stack = []

            this.combination(arr, 0, m, m, res, stack)

            stack.map((n) => {

                //临时栈，存放过程
                let tmp = []

                let maxPerLottery = 1

                //计算出排列组合并且求出最大最小赔率
                this.arrangement(n, 0, tmp, this.result)

                maxPerLottery = new Decimal((2 * this.multiply)).mul(new Decimal(this.maxOdds))
                this.maxLottery = new Decimal(this.maxLottery).add(maxPerLottery).toNumber()
                this.maxOdds = 0
            })
            this.maxLottery = this.maxLottery.toFixed(2)
        })
    },
    calculateMchuanNRecursion: function (arr, standardValue, m) {
        //存放索引号
        let res = []

        //存放最后的结果
        let stack = []

        this.combination(arr, 0, m, m, res, stack)

        stack.map((n) => {
            this.calculateMchuanN(n, standardValue)
        })
    },
    calculateValue: function (combineValue) {
        var value = []
        switch (combineValue) {
            case "3串3":
                value = [2]
                break;
            case "3串4":
                value = [2, 3]
                break;
            case "4串4":
                value = [3]
                break;
            case "4串5":
                value = [3, 4]
                break;
            case "4串6":
                value = [2]
                break;
            case "4串11":
                value = [2, 3, 4]
                break;
            case "5串5":
                value = [4]
                break;
            case "5串6":
                value = [4, 5]
                break;
            case "5串10":
                value = [2]
                break;
            case "5串16":
                value = [3, 4, 5]
                break;
            case "5串20":
                value = [2, 3]
                break;
            case "5串26":
                value = [2, 3, 4, 5]
                break;
            case "6串6":
                value = [5]
                break;
            case "6串7":
                value = [5, 6]
                break;
            case "6串15":
                value = [2]
                break;
            case "6串20":
                value = [3]
                break;
            case "6串22":
                value = [4, 5, 6]
                break;
            case "6串35":
                value = [2, 3]
                break;
            case "6串42":
                value = [3, 4, 5, 6]
                break;
            case "6串50":
                value = [2, 3, 4]
                break;
            case "6串57":
                value = [2, 3, 4, 5, 6]
                break;
            case "7串7":
                value = [6]
                break;
            case "7串8":
                value = [6, 7]
                break;
            case "7串21":
                value = [2]
                break;
            case "7串35":
                value = [3]
                break;
            case "7串120":
                value = [2, 3, 4, 5, 6, 7]
                break;
            case "8串8":
                value = [7]
                break;
            case "8串9":
                value = [7, 8]
                break;
            case "8串28":
                value = [6]
                break;
            case "8串56":
                value = [5]
                break;
            case "8串70":
                value = [4]
                break;
            case "8串247":
                value = [2, 3, 4, 5, 6, 7, 8]
                break;

        }
        return value
    },
    calculateResult: function () {
        this.betCnt = this.result.length
        //投注金额 = 注数 * 倍数 * 2
        this.betAmount = this.betCnt * this.multiply * 2
        this.minLottery = new Decimal((2 * this.multiply)).mul(new Decimal(this.minOdds)).toNumber().toFixed(2)

        this.resultInfo.betAmount = this.betAmount
        this.resultInfo.minLottery = this.minLottery
        this.resultInfo.maxLottery = this.maxLottery
        this.resultInfo.multiply = this.multiply
        this.resultInfo.betCnt = this.betCnt
        this.resultInfo.betType = "几串几"
        this.resultInfo.result = this.result



        console.log("注数:" + this.betCnt, "共" + this.betAmount + "元", "最低奖金" + this.minLottery, "最高奖金" + this.maxLottery, this.resultInfo) // 预计奖金

    }

    //这边是计算赔率的核心区域
  }
};
</script>

<style lang="scss" scoped>
.header {
  height: 80rpx;
  background: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .left,
  .right {
    width: 200rpx;
    height: 60rpx;
    border: 2rpx solid #f0f0f0;
    border-radius: 4rpx;
    color: grey;
    line-height: 60rpx;
    text-align: center;
    font-size: 24rpx;
  }
}
.content {
  margin: 30rpx;
  font-size: 24rpx;
  .item {
    padding: 20rpx;
    background: #fff;
    border-bottom: 2rpx solid #f0f0f0;
    height: 145rpx;

    .item-top {
      padding-right: 100rpx;
      display: flex;
      .left {
        width: 100rpx;
      }
      .right {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;
      }
    }
    .item-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 10rpx;
      .left,
      .right {
        width: 100rpx;
      }
      .left {
        line-height: 30rpx;
      }
      .right {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        text {
          width: 60rpx;
          height: 60rpx;
          border: 2rpx solid #f0f0f0;
          color: #ddd;
          line-height: 60rpx;
          text-align: center;
          display: block;
        }
      }
      .mid {
        flex: 1;
        height: 60rpx;
        color: #cb3a35;
        line-height: 60rpx;
        text-align: center;
        background: #dddddd;
      }
    }
  }
}

.bottom {
  width: 100%;
  background: #fff;
  box-shadow: 0 4rpx 12rpx 0 rgba(#000000, 0.1);
  position: fixed;
  bottom: 0;
  left: 0;
  .one,
  .two {
    height: 80rpx;
    border-top: 2rpx solid #eee;
    text-align: center;
    line-height: 40rpx;
    .top {
      font-size: 26rpx;
      color: grey;
    }
    .bot {
      font-size: 24rpx;
      color: #dddddd;
    }
  }
  .one {
    display: flex;
    .left,
    .right {
      width: 200rpx;
      font-size: 28rpx;
      color: grey;
      line-height: 80rpx;
      text-align: center;
    }
		.left {
			display: flex;
			justify-content: center;
			.ctitCss {
				width: 136rpx;
				display: inline-block;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
    .mid {
      flex: 1;
      border-right: 2rpx solid #eee;
      border-left: 2rpx solid #eee;
      display: flex;
      justify-content: center;
      align-items: center;
      text {
        color: grey;
        padding: 0 10rpx;
      }
    }
  }
  .three {
    height: 100rpx;
    border-top: 2rpx solid #eee;
    display: flex;
    .left {
      flex: 1;
      line-height: 100rpx;
      color: #cb3a35;
      padding-left: 50rpx;
    }
    .right {
      width: 200rpx;
      background: #cb3a35;
      color: #fff;
      line-height: 100rpx;
      text-align: center;
    }
  }
}

.wrap {
  border-top: 2rpx solid #eee;
  padding: 0 20rpx;
  max-height: 210px;
  height: 100%;
  overflow: scroll;
  .title {
    padding: 20rpx 10rpx;
  }
  .col-item {
    height: 80rpx;
    color: grey;
    border: 2rpx solid #f0f0f0;
    margin-bottom: 20rpx;
    line-height: 80rpx;
    text-align: center;
  }
}
.on {
  background: #cb3a35;
  color: #fff !important;
  border: none !important;
}
</style>